package juc.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @program: check-repetition
 * @description:
 * @author: hjk
 * @create: 2021-07-12 18:16
 **/
public class SemaphoreDemo {
    /**
     * 抢车位, 10 部汽车 3 个停车位
     * @param args
     */
    public static void main(String[] args) throws Exception{
        //定义 3 个停车位
        Semaphore semaphore = new Semaphore(3);
        //模拟 6 辆汽车停车
        for (int i = 1; i <= 10; i++) {
            Thread.sleep(100);
            //停车
            new Thread(() ->{
                try {
                    System.out.println(Thread.currentThread().getName() + "找车位 ing");
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "汽车停车成 功!");
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    System.out.println(Thread.currentThread().getName() + "溜了溜了");
                    semaphore.release();
                }
            }, "汽车" + i).start();
        }
    }
}
